<?php

namespace Ruben\Payment;

class ApplePay
{
    static $isSandbox = false;

    public static function useSandbx()
    {
        $this->isSandbox = true;
    }

    public function verify($receipt, $transactionId)
    {
        $data = $this->getReceiptData($receipt, $this->isSandbox);
        return $data;
    }

    private function getReceiptData($receipt, $isSandbox = false){
        if ($isSandbox) {
            $endpoint = 'https://sandbox.itunes.apple.com/verifyReceipt';//沙箱地址
        } else {
            $endpoint = 'https://buy.itunes.apple.com/verifyReceipt';//真实运营地址
        }
        $postData = json_encode(
            array('receipt-data' => $receipt)
        );
        $ch = curl_init($endpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);  
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        $response = curl_exec($ch);
        $errno    = curl_errno($ch);
        curl_close($ch);
        if ($errno != 0) {//curl请求有错误
            $this->ajaxerror('请求超时，请稍后重试');
        }else{
            $data = json_decode($response, true);
            if(isset($data['status'])){
                //返回产品的信息
                $order = $data['receipt']['in_app'][0];
                $order['status']=$data['status'];
            }else{
                $order['status']=30000;
            }            
            return $order;
        }

    }
}